package com.EVO.listener;

import com.EVO.util.Util;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class Listener1 implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        Connection conn = null;
        Map map = new HashMap();
        for(int i=0;i<20;i++){
            try {
                conn = Util.getConnection();
                System.out.println("Http服务器启动时创建Connection: "+conn);
                map.put(conn,true);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            ServletContext application = sce.getServletContext();
            application.setAttribute("key1",map);
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        ServletContext application = sce.getServletContext();
        Map map = (Map)application.getAttribute("key1");
        Iterator it = map.entrySet().iterator();
        while(it.hasNext()){
            Connection conn = (Connection)it.next();
            Util.close(conn,null,null);
        }
    }
}
